

package com.asisto.controller

import com.asisto.model.*

class ServicioController {


    def jornadasService
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ servicioInstanceList: Servicio.list( params ), servicioInstanceTotal: Servicio.count() ]
    }

    def show = {
        def servicioInstance = Servicio.get( params.id )

        if(!servicioInstance) {
            flash.message = "Servicio not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ servicioInstance : servicioInstance ] }
    }

    def delete = {
        def servicioInstance = Servicio.get( params.id )
        if(servicioInstance) {
            try {
                servicioInstance.delete(flush:true)
                flash.message = "Servicio ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Servicio ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Servicio not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def servicioInstance = Servicio.get( params.id )

        if(!servicioInstance) {
            flash.message = "Servicio not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ servicioInstance : servicioInstance ]
        }
    }

    def update = {
        def servicioInstance = Servicio.get( params.id )
        if(servicioInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(servicioInstance.version > version) {
                    
                    servicioInstance.errors.rejectValue("version", "servicio.optimistic.locking.failure", "Another user has updated this Servicio while you were editing.")
                    render(view:'edit',model:[servicioInstance:servicioInstance])
                    return
                }
            }
            servicioInstance.properties = params
            if(!servicioInstance.hasErrors() && servicioInstance.save()) {
                flash.message = "Servicio ${params.id} updated"
                redirect(action:show,id:servicioInstance.id)
            }
            else {
                render(view:'edit',model:[servicioInstance:servicioInstance])
            }
        }
        else {
            flash.message = "Servicio not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def create = {
        def servicioInstance = new Servicio()
        servicioInstance.properties = params
        return ['servicioInstance':servicioInstance]
    }

    def save = {
        def servicioInstance = new Servicio(params)
        if(!servicioInstance.hasErrors() && servicioInstance.save()) {
            flash.message = "Servicio ${servicioInstance.id} created"
            redirect(action:show,id:servicioInstance.id)
        }
        else {
            render(view:'create',model:[servicioInstance:servicioInstance])
        }
    }


    def peticionFlow = {

        

        seleccionCliente {
            
            on('next') {
                String idCliente = params?.cliente
                println "cliente = $idCliente"
                flow.idCliente = idCliente
                [nombreCliente:idCliente]
            }.to('compruebaCliente')

            on('cancel').to('finish')
        }


        compruebaCliente {
            action{
                def idCliente = flow.idCliente
                println "id de cliente: $idCliente"
                if (idCliente == '0') {
                    println "es un cliente nuevo"
                    clienteNuevo()
                } else {
                    println "es un cliente existente"
                    clienteExistente()
                }
            }
            on('clienteNuevo').to('datosCliente')
            on('clienteExistente') {

                def idCliente = flow.idCliente
                println "id de cliente: $idCliente"

                //Obtiene los datos del cliente
                Cliente cliente = Cliente.get(idCliente)

                [cliente:cliente]

            }.to('datosCliente')
            
        }

        datosCliente {

            on('next') {
                [clienteid:flow.idCliente]
            }.to('seleccionJornadas')

            on('cancel').to('finish')
        }

        seleccionJornadas {
            on('finished'){
                def idCliente = flow.idCliente
                println "cliente al final de todo: $idCliente"
                println "params : $params"

                def fechas = params.fechas


                Cliente cliente = Cliente.get(idCliente)

                if (fechas && cliente) {
                    def mapaFechas = obtieneFechas(fechas)

                    if (mapaFechas) {
                        jornadasService.creaJornadas(mapaFechas, cliente)
                    }
                }

                [mensaje:'Jornadas creadas']


            }.to('finish')
        }


        finish {
            render(view:"/index")
        }


        


    }


    def obtieneFechas(String cadena) {

        
        def valores = cadena.split(';')

        def mapaFechas = [:]
        
        valores.each {

            def lasHoras = []
            println "valor: $it"
            def vals = it.split(":")
            String fecha = vals[0]
            String horas = ''

            if (vals.size()==2) {
                horas = vals[1]
            } 

            if (horas) {

                def horaInicio = ''
                def horaFin = ''

                def hs = []
                hs = horas.split(',')

                hs.each {
                    def map = [:]
                    (horaInicio, horaFin) = it.split('-')

                    map.horaInicio = horaInicio
                    map.horaFin = horaFin


                    lasHoras.add(map)
                }


            }

            println "fecha: $fecha - horas: $lasHoras"
            mapaFechas.put(fecha,lasHoras)


        } //fin closure each

        return mapaFechas

    }
}
